<?php

namespace addons\classroom\library;
use fast\Http;
use think\Controller;
use think\Db;


class Qwechat extends Controller
{
    protected $corpid = "";
    protected $corpsecret = "";
    protected $AgentId = "";
    public $token = "";

    public function _initialize()
    {
        parent::_initialize();

        $qwechat_config = get_addon_config('classroom');
        $this->corpid = $qwechat_config['qy_wechat_appid'];// 企业ID
        $this->corpsecret = $qwechat_config['qy_wechat_secret'];
        $this->AgentId = $qwechat_config['qy_wechat_agentid'];
    }

    /**
     * 获取应用token
     * @param string $corpid 企业ID
     * @param string $corpsecret 应用的凭证密钥
     * @return mixed|string
     */
    public function get_token($corpid,$corpsecret)
    {
        $request = new Http();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={$corpid}&corpsecret={$corpsecret}";
        $data = $request->get($url);
        $data = json_decode($data,true);
        return $data['access_token'];
    }


    /**
     * 微信扫码登陆
     * @param string $code 微信扫码返回值
     * @return array
     */
    public function wechat_login($code)
    {
        $access_token = $this->get_token($this->corpid,$this->corpsecret);
        $request = new Http();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$access_token}&code={$code}";
        $data = $request->get($url);
        $data = json_decode($data,true);
        if($data['errcode'] != 0){
            return ["code"=>0,"msg"=>$data['errmsg']];
        }
        return ["code"=>1,"msg"=>$data['errmsg'],"UserId"=>$data['UserId']];
    }

    /**
     * 通过用户ID，获取用户详情
     */
    public function getUser($UserId)
    {
        $access_token = $this->get_token($this->corpid,$this->corpsecret);
        $request = new Http();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={$access_token}&userid={$UserId}";
        $data = $request->get($url);
        $data = json_decode($data,true);
        if($data['errcode'] != 0){
            return ["code"=>0,"msg"=>$data['errmsg']];
        }
        return ["code"=>1,"msg"=>$data['errmsg'],"data"=>$data];
    }


}







